// pages/settings/index.js
wx.cloud.init({
  traceUser: true
})
const db = wx.cloud.database()
const user = db.collection('user')
const app = getApp()

let avatarEnd = false
let bgEnd = false
let otherEnd = false
let clickFlag = false
import { getImageCache } from '../../utils/imageCache.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    avatarSrc: '',
    avatarState: false,
    beforeAvatar: '',
    bgSrc: '',
    beforeBg: '',
    bgState: false,
    avatarFile: '',
    bgpicFile: '',
    username: '',
    sex: 0,
    oneword: '',
    tagName: '',
    tag: [],
    colorList: ['blue', 'green', 'orange', 'red', 'mauve'],

    avatarCache: '',
    bgCache: ''
  },

  getUsername(e){
    this.setData({
      username: e.detail.value
    })
  },

  getOneword(e) {
    this.setData({
      oneword: e.detail.value
    })
  },

  getSex(e) {
    this.setData({
      sex: Number(e.detail.value)
    })
  },

  getTagname(e) {
    this.setData({
      tagName: e.detail.value
    })
  },

  addTag(){
    if (this.data.tag.length == 4) return
    if (this.data.tagName.trim() == '') return
    this.data.tag.push({
      name: this.data.tagName,
      tagId: app.userDataId + new Date().getTime()
    })
    this.setData({
      tag: this.data.tag,
      tagName: ''
    })
  },

  deleteTag(e){
    this.data.tag.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      tag: this.data.tag
    })
  },

  ChooseImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          avatarSrc: res.tempFilePaths[0],
          avatarState: true
        })
      }
    });
  },
  ChooseBgImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          bgSrc: res.tempFilePaths[0],
          bgState: true
        })
      }
    });
  },

  comfireModified(){
    if (clickFlag) return //防抖处理
    else clickFlag = true
    this.setData({
      loading: true
    })
// 必须先删除以前的上传路径，再加入新的，覆盖之前的路径会导致页面不更新需要清除缓存后才能显示正常
// 服务端上传的文件无法显示，应该是路径不对
    if (this.data.avatarState) {
      wx.cloud.deleteFile({ 
        fileList: [this.data.beforeAvatar]
      }).then(res => {
        wx.cloud.uploadFile({
          cloudPath: 'userAvatar/' + app.userDataId + '/' + new Date().getTime(),
          filePath: this.data.avatarSrc, // 文件路径
        }).then(res => {
          this.setData({
            avatarFile: res.fileID
          })
          wx.removeStorage({
            key: 'avatar-' + app.userDataId,
            success(res) {
              // console.log(res)
            }
          })
          getImageCache('avatar-' + app.userDataId, res.fileID).then(res => {
            // console.log(res)
          })
          user.doc(app.userDataId).update({
            data: {
              avatar: res.fileID
            },
            success: res => {
              avatarEnd = true
              this.modifiedEnd()
            }
          })
        }).catch(error => {
          console.log('头像上传失败！' + error)
        })
      }).catch(error => {
        console.log('头像删除失败！' + error)
      })
    }else{
      avatarEnd = true
    }

    if (this.data.bgState) {
      wx.cloud.deleteFile({
        fileList: [this.data.beforeBg]
      }).then(res => {
        wx.cloud.uploadFile({
          cloudPath: 'bgSrc/' + app.userDataId + '/' + new Date().getTime(),
          filePath: this.data.bgSrc, // 文件路径
        }).then(res => {
          this.setData({
            bgpicFile: res.fileID
          })
          wx.removeStorage({
            key: 'bg-' + app.userDataId,
            success(res) {
              // console.log(res)
            }
          })
          getImageCache('bg-' + app.userDataId, res.fileID).then(res => {
            // console.log(res)
          })
          user.doc(app.userDataId).update({
            data: {
              bgpic: res.fileID
            },
            success: res => {
              bgEnd = true
              this.modifiedEnd()
            }
          })
        }).catch(error => {
          console.log('背景上传失败！' + error)
        })
      }).catch(error => {
        console.log('背景删除失败！' + error)
      })
    }else{
      bgEnd = true
    }

    user.doc(app.userDataId).update({
      data: {
        username: this.data.username,
        sex: this.data.sex,
        oneword: this.data.oneword,
        tag: this.data.tag
      },
      success: res => {
        otherEnd = true
        this.modifiedEnd()
      }
    })

  },

  modifiedEnd (){
    if (avatarEnd && bgEnd && otherEnd) {
      clickFlag = false
      this.setData({
        loading: false
      })
      app.user = {
        _openid: app.user._openid,
        username: this.data.username,
        sex: this.data.sex,
        oneword: this.data.oneword,
        tag: this.data.tag,
        avatar: this.data.avatarFile == '' ? this.data.beforeAvatar : this.data.avatarFile,
        bgpic: this.data.bgpicFile == '' ? this.data.beforeBg : this.data.bgpicFile
      }
      wx.redirectTo({
        url: '/pages/index/index?component=userSetting',
      })
      // console.log('end')
    } else {
      // console.log('wait')
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getStorage({
      key: 'avatar-' + app.userDataId,
      success: (res) => {
        this.setData({
          avatarCache: res.data
        })
      }
    })
    wx.getStorage({
      key: 'bg-' + app.userDataId,
      success: (res) => {
        this.setData({
          bgCache: res.data
        })
      }
    })
    // let bgCache = wx.getStorageSync('bg-' + app.userDataId)
    this.setData({
      beforeAvatar: app.user.avatar,
      beforeBg: app.user.bgpic,
      bgSrc: app.user.bgpic != '' ? app.user.bgpic : 'https://636f-conch-voice-test-8c0757-1259463971.tcb.qcloud.la/bg.jpeg?sign=936540ee1e18986d2d7ac1ba0eba1b03&t=1560861319',
      username: app.user.username,
      sex: app.user.sex,
      oneword: app.user.oneword,
      tag: app.user.tag
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})